<?php

namespace App\Http\Controllers\Saas;

use App\Contract\ContractStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreateHouseRequest;
use App\Http\Resources\HousePaginationCollection;
use App\Model\Device;
use App\Model\House;
use App\Utils\Result;
use App\Utils\Token;
use Illuminate\Http\Request;

class HouseController extends Controller
{
    public function index(Request $request)
    {
        // Get the current page number from the request parameters (default to 1)
        $page = $request->input('page', 1);

        // Get the number of houses to show per page
        $perPage = $request->input('pageSize', 20);

        $keyword = $request->input('keyword');
        $province = $request->input('province');
        $city = $request->input('city');
        $district= $request->input('district');
        $estate_name = $request->input('estate_name');
        $businessName = $request->input('businessName');
        $country = $request->input('country');
        $sn = $request->input('sn');
        $query = House::query();
        $status = $request->input('status');
        $has_device1 = $request->input('has_device1');
        $user = $this->getUser();
        if($user->roles != 'admin' && (!$keyword && !$businessName && !$sn & !$province & !$city & !$district & !$estate_name &!$country)){
            return Result::success([]);
        }
        if ($sn) {
            $query->whereHas('device', function ($q) use ($sn) {
                $q->where('sn', $sn);
            });
        }
        if ($status == 'hired') {
            $query->whereHas('contract', function($q) {
                $q->where('status', ContractStatus::YIQIANYUE);
            });
        }
        if ($status == 'vacant') {
            $query->whereDoesntHave('contract', function($q) {
                $q->where('status', ContractStatus::YIQIANYUE);
            });
        }
        if ($status == 'expire') {
            $query->whereHas('contract', function($q) {
                $q->where('status', ContractStatus::YIQIANYUE);
                $q->where('expired_at', '<', now()->addDays(30)->toDateString());
            });
        }
        if ($has_device1 == 'no') {
            $query->whereDoesntHave('device', function($q) {
                $q->where('type', 1);
            });
        }
        if ($keyword) {
            $query->where('name', 'like', "%{$keyword}%");
        }
        if ($province) {
            $query->where('province', 'like', "%{$province}%");
        }
        if ($city) {
            $query->where('city', 'like', "%{$city}%");
        }
        if ($district) {
            $query->where('district', 'like', "%{$district}%");
        }
        if($country){
            $query->where('country', 'like', "%{$country}%");
        }
        if ($businessName) {
            $query->whereHas('business', function($q) use ($businessName) {
                $q->where('name', $businessName);
            })->orWhereHas('business.user', function($q) use ($businessName) {
                $q->where('mobile', $businessName);
            });
        }
        if ($estate_name) {
            $estate_names = explode(' ', $estate_name);
            $query->where(function ($q) use ($estate_names) {
                foreach ($estate_names as $k => $name) {
                    if($k == 0){
                        $q->where('estate_name', 'like', "%{$name}%");
                    }else{
                        $q->orWhere('estate_name', 'like', "%{$name}%");
                    }
                }
            });
        }
        // Get a paginated collection of House models from the database
        $houses = $query->with('contract', 'contract.contractTenant', 'device', 'business', 'business.user')
            ->orderByDesc('id')
            ->paginate($perPage, ['*'], 'page', $page);

        return Result::success(new HousePaginationCollection($houses));
    }

    public function detail($id)
    {
        $house = House::query()->with('contract', 'contract.contractTenant', 'contract.contractRent', 'device')->find($id);
        return Result::success($house);
    }

    public function update(Request $request, $id)
    {
        $house = House::query()->where('id', $id)->first();
        if (!$house) {
            return Result::error(404, '未找到记录');
        }
        $data = $request->all();
        $house->fill($data);
        $house->save();
    }

    public function destroy($id)
    {
        $house = House::query()->with('contract')->find($id);

        if ($house->contract) {
            return Result::error(400, '房源已创建合同，无法删除');
        }

        $house->delete();

        return Result::success();
    }
}
